package com.why.simpleboot.core.common.utils;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: why-simpleboot-framework
 * @description:
 * @author: @why
 * @create: 2021-05-22 18:18
 **/
public class UrlUtils {
    /**
     * url转为正则模式
     *
     * @param url:给定的url会被改变。 eg: /user/name ---> ^/user/name?&
     *                        /user/{name}-->^/user/[\u4e00-\u9fa5_a-zA-Z0-9]+/?$
     * @return
     */
    public static String formatUrl(String url) {
        String originPattern = url.replaceAll("(\\{\\w+})", "[\\\\u4e00-\\\\u9fa5_a-zA-Z0-9]+");
        String pattern = "^?" + originPattern + "/?$";
        return pattern.replaceAll("/+", "/");
    }

    /**
     * 完成路径参数的匹配操作
     * 请求参数 /user/why
     *
     * @param requestPath：请求的参数 eg:  /user/why
     * @param url:本地map中所对应的原始url: /user/{name}
     * @return: user=user,  name=why
     */
    public static Map<String, String> getUrlParameterMappings(String requestPath, String url) {
        String[] requestParams = requestPath.split("/");
        String[] urlParams = url.split("/");
        Map<String, String> urlParameterMappings = new HashMap<>();
        for (int i = 1; i < urlParams.length; i++) {
            urlParameterMappings.put(urlParams[i].replace("{", "").replace("}", ""), requestParams[i]);
        }
        return urlParameterMappings;
    }


}
